package com.handpay.nocardpay.baselibrary.raindrops;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.model.bean.BaseErrorInfo;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.raindrops.model.bean.AuthResult;
import com.handpay.nocardpay.baselibrary.raindrops.presenter.RainDropsPresenterImpl;
import com.handpay.nocardpay.baselibrary.raindrops.view.IAuthView;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.main.mine.model.bean.MerchInfo;
import com.handpay.nocardpay.baselibrary.main.mine.presenter.MinePresenterImpl;
import com.handpay.nocardpay.baselibrary.main.mine.view.IMerchInfoView;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sxshi on 2018-4-23.
 *         小雨滴网贷页面
 */

public class RainDropsFragment extends BaseFragment implements IMerchInfoView, IAuthView {

    private WebView mWebView;
    private MHandler mHandler = new MHandler();
    private MyWebViewClient myWebViewClient;
    public static String newBankFlag = "1";
    //获取商户信息

    private MinePresenterImpl minePresenter;

    private RainDropsPresenterImpl rainDropsPresenter;


    private String xrId;

    public static RainDropsFragment newInstance() {
        Bundle args = new Bundle();
        RainDropsFragment fragment = new RainDropsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_raindrops;
    }

    @Override
    public String getFragmentTitle() {
        return _mActivity.getResources().getString(R.string.dfpay);
    }

    @Override
    public void initView(View view) {
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolbar(toolbar, true);
        mWebView = (WebView) view.findViewById(R.id.wv_content);
        myWebViewClient = new MyWebViewClient(_mActivity, mHandler);
        mWebView.setWebViewClient(myWebViewClient);
        mWebView.clearHistory();
        mWebView.clearMatches();
        mWebView.clearFormData();
        mWebView.clearCache(true);
        removeCookie(_mActivity);

        WebSettings settings = mWebView.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

        settings.setUseWideViewPort(true);//设置webview推荐使用的窗口，设置为true
        settings.setLoadWithOverviewMode(true);   //自适应屏幕
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);

        settings.setAllowFileAccess(true); //设置可以访问文件
        settings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        settings.setLoadsImagesAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
            settings.setAllowUniversalAccessFromFileURLs(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setAllowContentAccess(true);
        settings.setDomStorageEnabled(true);//开启DOM
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new JsInterface(), "senderModel");
        myWebViewClient.setShowLoading(true);

        minePresenter = new MinePresenterImpl(_mActivity);
        minePresenter.setiMerchInfoView(this);

        rainDropsPresenter = new RainDropsPresenterImpl(_mActivity);
        rainDropsPresenter.setAuthView(this);
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        PreferenceManager.getInstance(_mActivity).putBoolean("RainDrops_" + AccountUtils.getAccountPhone(_mActivity), true);
        queryMerchInfo();
    }

    @Override
    public void onDestroy() {
        myWebViewClient.destory();
        mWebView.stopLoading();
        mWebView.clearMatches();
        mWebView.destroy();
        rainDropsPresenter.onDestory();
        super.onDestroy();
    }

    /**
     * 手动清除Session
     *
     * @param context
     */
    private void removeCookie(Context context) {
        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.setAcceptThirdPartyCookies(mWebView, true);
            cookieManager.removeSessionCookies(new ValueCallback<Boolean>() {
                @Override
                public void onReceiveValue(Boolean value) {
                    HPLog.d(HPLog.SSX_TAG, "onReceiveValue: removeSessionCookies");
                }
            });
            cookieManager.flush();
        }
    }

    @Override
    public void showErrorAlert(BaseErrorInfo baseErrorInfo) {
        DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), baseErrorInfo.errMessage, false, _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                pop();
            }
        });
    }

    /**
     * 获取当前用户信息
     */
    public void queryMerchInfo() {
        HashMap<String, Object> params = new HashMap<>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(_mActivity), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, newBankFlag);
        if (minePresenter != null) {
            minePresenter.getMerchInfo(params, MerchInfo.class, false);
        }
    }

    @Override
    public void querySuccess(MerchInfo merchInfo) {
        String name = SecureManager.getInstance().des(merchInfo.getName(), 0, null);
        String bankName = SecureManager.getInstance().des(merchInfo.getBankName(), 0, null);
        String cardNum = SecureManager.getInstance().des(merchInfo.getCardNum(), 0, null);
        String mSubBankName = SecureManager.getInstance().des(merchInfo.getSubBranchName(), 0, null);
        String certNo = SecureManager.getInstance().des(merchInfo.getCertNo(), 0, null);
        String mSubBankCode = merchInfo.getSubBankCode();//服务器未加密
        merchInfo.setName(name);
        merchInfo.setBankName(bankName);
        merchInfo.setCardNum(cardNum);
        merchInfo.setSubBranchName(mSubBankName);
        merchInfo.setSubBankCode(mSubBankCode);
        AccountUtils.saveUserName(_mActivity, name);
        AccountUtils.setAccountStatus(_mActivity, AccountUtils.convertStatus(merchInfo.getStatus()));
        String phone = SecureManager.getInstance().des(merchInfo.getPhone(), 0, null);
        AccountUtils.setAccountPhone(_mActivity, phone);
        AccountUtils.saveUsercertNo(_mActivity, certNo);

        getAuthStatus();
    }

    /**
     * 小雨点认证：
     */
    public void getAuthStatus() {
        String des3Key = NoCardPayConfig.SMARTPAY_3DESKEY;
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> sinparam = new HashMap<>();
        String requestPath = "xyd/auth/" + NoCardPayConfig.CHANNEL;
        String realName = null;// 需要URLEncoder.encode
        try {
            realName = java.net.URLEncoder.encode(AccountUtils.getUserName(_mActivity), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String phone = SecureManager.getInstance().des(AccountUtils.getAccountPhone(_mActivity), 1, des3Key);// 需要指定3des加密
        sinparam.put(BaseProtocolKey.NAME, AccountUtils.getUserName(_mActivity));
        sinparam.put(BaseProtocolKey.MOBILE, AccountUtils.getAccountPhone(_mActivity));
        sinparam.put(BaseProtocolKey.CHANNEL_CODE, NoCardPayConfig.CHANNEL);
        String sign = RainDropsSign.getSign(NoCardPayConfig.CHANNEL, AccountUtils.getAccountPhone(_mActivity), AccountUtils.getUserName(_mActivity));
        param.put(BaseProtocolKey.CHANNEL_CODE, NoCardPayConfig.CHANNEL);
        param.put(BaseProtocolKey.NAME, realName);
        param.put(BaseProtocolKey.SIGN, sign);
        param.put(BaseProtocolKey.MOBILE, phone);

        rainDropsPresenter.getAuthResult(requestPath, param, false);
    }

    @Override
    public void getAuthResult(AuthResult authResult) {
        if (authResult != null) {
            mWebView.loadUrl(authResult.getXydUrl());
            xrId = authResult.getXrId();
        }
    }


    class JsInterface {
        @JavascriptInterface
        public void errorReload() {
            _mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    myWebViewClient.setShowLoading(true);
                    if (myWebViewClient.getmFailingUrl() != null) {
                        mWebView.loadUrl(myWebViewClient.getmFailingUrl());
                    }
                }
            });
        }
    }

    class MHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (Constants.WEBVIEW_ERROR == msg.what) {
                if (mWebView.getProgress() < 100) {
                    mWebView.stopLoading();
                    mWebView.loadUrl("file:///android_asset/error.html");
                }
            } else if (Constants.NOTICE_UPLOAD == msg.what) {
                if (!TextUtils.isEmpty(xrId)) {
                    //通知后台上传pdf
                    String requestPath = "xyd/upload/" + xrId;
                    String sign = RainDropsSign.getXrIdSign(xrId);
                    Map<String, Object> param = new HashMap<>();
                    param.put("xrId", xrId);
                    param.put(BaseProtocolKey.SIGN, sign);
                    rainDropsPresenter.noticeUpload(requestPath, param);
                }
            }
        }
    }
}
